<template>
  <div>
    <van-cell
      icon="search"
      v-for="(item, index) in hightLightSuggestions"
      :key="index"
      @click="$emit('update-keywords', suggestions[index])"
    >
      <template #title>
        <span v-html="item"></span>
      </template>
    </van-cell>
  </div>
</template>
<script>
import { getSuggestionsAPI } from '@/api'
import { debounce } from 'lodash'
export default {
  props: {
    keywords: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      suggestions: []
    }
  },
  watch: {
    keywords: {
      handler: 'getSearchSuggestions',
      immediate: true
    }
  },
  computed: {
    //map方法
    // - 返回值 跟原数组长度一致的新数组

    //动态正则
    // - 字面量的正则 /a/ 缺点：正则公式写死的
    // - RegExp --> regular expression new RegExp(正则内容字符串，修饰符字符串)

    //字符串的replace
    //返回值：替换后的新字符串
    // - replace(子字符串，替换的字符串)
    // - replace(正则，替换的字符串)
    // - replace(正则，函数) 函数的返回值作为替换的结果，match函数的参数，放回正则匹配的结果
    hightLightSuggestions() {
      const reg = new RegExp(this.keywords, 'ig')
      return this.suggestions.map((str) => {
        //item:Angular
        return str.replace(
          reg,
          (match) => `<span style='color:red'>${match}</sapn>`
        )
      })
    }
  },
  methods: {
    // getSearchSuggestions() {
    //   clearTimeout(this.id)
    //   this.id = setTimeout(async () => {
    //     const { data } = await getSuggestionsAPI(this.keywords)
    //     this.suggestions = data.data.options.filter(Boolean)
    //   }, 300)

    //   const { data } = await getSuggestionsAPI(this.keywords)
    //   this.suggestions = data.data.options.filter((item) => Boolean(item))
    //window.Boolean = function(arg1) {return boolean}
    //   this.suggestions = data.data.options.filter(Boolean)
    // }

    getSearchSuggestions: debounce(async function () {
      const { data } = await getSuggestionsAPI(this.keywords)
      this.suggestions = data.data.options.filter(Boolean)
    }, 300)
  }
}
</script>

<style></style>
